package com.oneguy.control.queue;


import com.oneguy.Log;

public class Handler implements Runnable {
    private static final String TAG = "Handler";
    private MessageQueue messageQueue;
    private boolean running;
    private Thread mThread;
    private static final int MESSAGE_PROCESS_INTERNAL = 500;

    public Handler() {
        messageQueue = new MessageQueue();
        running = true;
        mThread = new Thread(this, "Handler");
        mThread.start();
    }

    public void quit() {
        running = false;
        if (mThread != null) {
            mThread.interrupt();
            mThread = null;
        }
    }

    public void handleMessage(Message msg) {
    }

    public void sendMessageDelayed(Message msg, long delay) {
        synchronized (messageQueue) {
            long now = System.currentTimeMillis();
            msg.setWhen(now + delay);
            messageQueue.offer(msg);
            messageQueue.notifyAll();
        }
    }

    public void sendEmptyMessageDelayed(int what, long delay) {
        Message msg = new Message();
        msg.what = what;
        sendMessageDelayed(msg, delay);
    }

    @Override
    public void run() {
        while (running) {
            Message msg = null;
            Message proccessMsg = null;
            synchronized (messageQueue) {
                msg = messageQueue.peek();
                long now = System.currentTimeMillis();
//                Log.i(TAG, "now" + now + " when:" + msg.getWhen() + " " + (now - msg.getWhen()));
                if (msg != null && msg.getWhen() <= now) {
                    messageQueue.poll();
                    proccessMsg = msg;
                } else {
                    try {
                        messageQueue.wait(MESSAGE_PROCESS_INTERNAL);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (proccessMsg != null) {
                handleMessage(proccessMsg);
            }
        }
    }

    public void sendMessage(Message msg) {
        sendMessageDelayed(msg, 0);
    }

    public void sendEmptyMessage(int what) {
        sendEmptyMessageDelayed(what, 0);
    }

}
